
import { losChannelKs } from "./losChannelKs";
import { losChannelOppo } from "./losChannelOppo";
import { losChannelVivo } from "./losChannelVivo";
import { losChannelWeb } from "./losChannelWeb";
import { losChannelMi } from "./losChannelMi";
import loskc from "./loskc";
import { losChannelVivo1 } from "./losChannelVivo1";
import { losChannelKs2 } from "./losChannelKs2";
import { losChannelOppo1 } from "./losChannelOppo1";
import { losChannelMg } from "./losChannelMg";
import { losChannelHw } from "./losChannelHw";
import { losChannelKs3 } from "./losChannelKs3";
import { losChannelHonor } from "./losChannelHonor";

/**
 * 分渠道打包处理,出包时配置其中的channel值为渠道对象
 *
 */
export class losChannel {

    private static _me: losChannel;
    public static instance() {
        if (!losChannel._me) {
            losChannel._me = new losChannel();
        }
        return losChannel._me;
    }

    /** 统计需要的版本号 */
    static version = '1.0.1';

    static verMap = {
        'debug': {
            'id': '66bb1e786b79cf03e9a6d4b8',
        },
    };


    /** 当前渠道,出包在此配置渠道, 仅当remoteVerKey为debug时有效否则会变成web  */
    channel: string = 'hw';

    /** 是否读取远程配置,出正式包时设置为false,当remoteVerKey为debug时会自动设置为false */
    static isConfRemote: boolean = true;

    /** 读取远程,出包时必须配置为debug,此时isConfRemote为false */
    static remoteVerKey: string = 'debug';

    /** 游戏名称，用于远程存档,隐私政策等显示用 */
    static gameName: string = '';

    channelMap: Map<String, losChannelWeb> = new Map([
        ['web', new losChannelWeb()],
        // ['wx', new losChannelWx()],
        // ['wx1', new losChannelWx1()],
        // ['ios', new losChannelIOS()],
        ['oppo', new losChannelOppo()],
        ['oppo1', new losChannelOppo1()],
        ['vivo', new losChannelVivo()],
        ['vivo1', new losChannelVivo1()],
        ['xiaomi', new losChannelMi()],
        // ['alipay', new losChannelAlipay()],
        ['ks', new losChannelKs()],
        ['ks2', new losChannelKs2()],
        ['ks3', new losChannelKs3()],
        ['mg', new losChannelMg()],
        ['hw', new losChannelHw()],
        ['honor', new losChannelHonor()]
        // ['ks1', new losChannelKs1()],
        // ['taptap', new losChannelTap()],
        // ['noAD', new losChannelNoAD()],
        // ['mg', new losChannelMg()]
    ]);



    /**
     * 上传解密微信私密数据
     * @param appId 
     * @param encryptedData 加密数据
     * @param iv 加密iv
     * @param signature 加密签名
     * @param code 微信登录authCode
     * @param callback 
     */
    static decodeWxData(appId: string, encryptedData: string, iv: string, code: string, signature: string, callback: (data: Array<{ dataType: { type: number }, value: number }>) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/decodeWxData', { appId, encryptedData, iv, code, signature }, (err: any, re: any) => {
            if (err) {
                console.error(err);
                callback(null);
                return;
            }
            if (re.code !== 0) {
                callback(null);
                return;
            }
            callback(re.data && re.data.dataList);
        });
    }


    /**
     * 订阅消息
     * @param appId 
     * @param openId 
     * @param template_id 模板id
     * @param signDay 签到天数
     * @param callback 
     */
    static subMsg(appId: string, openId: string, template_id: string, signDay: number, callback: (code: number) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/wxOrderSubMsg', { appId, openId, template_id, signDay }, (err: any, re: any) => {
            if (err) {
                console.error(err);
                callback(-1);
                return;
            }
            if (re.code !== 0) {
                callback(-1);
                return;
            }
            callback(0);
        });
    }

    /**
     * 兑换码兑换
     * @param gameId 
     * @param userId 
     * @param redeemCode 兑换码
     * @param callback Array<{ key: string, val: string }> 如: [{key:'金币',val:'1000'},{key:'解锁',val:'weapon1'}]
     */
    static redeem(gameId: string, userId: string, redeemCode: string, callback: (arr: Array<{ key: string, val: string }>) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/redeem', { 'code': redeemCode, gameId, userId }, (err?: any, re?: any) => {
            if (err) {
                console.error(err);
                callback(null);
                return;
            }
            if (re.code !== 0) {
                callback(null);
                return;
            }

            const dataArr = loskc.strArr(re.data);
            if (!dataArr) {
                callback(null);
                return;
            }
            const out = [];
            for (let i = 0; i < dataArr.length; i++) {
                const arr = dataArr[i].split(':');
                if (arr.length < 2) {
                    console.error('兑换码配置有误', dataArr[i]);
                    continue;
                }
                out.push({ key: arr[0], val: arr[1] });
            }
            callback(out);
        });
    }

    /**
     * 拉取分享图,callback中返回Array<{ picId: string, picUrl: string, txt: string }>
     * @param gameId 
     * @param callback 
     */
    static getSharePics(gameId: string, callback: (arr: Array<{ picId: string, picUrl: string, txt: string }>) => void) {
        const reqObj = {
            'game': gameId,
            'query': 'aaa',
            'v': '1.2.0',
            's': 's',
        };
        this.instance().getChannel().jpost('https://dk.gametdd.com/htApi/ht_api/getSharePic', reqObj, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                callback([]);
                return;
            }
            // loskc.log('re', re);
            if (!re || (re.re != 0) || !re.data || re.data.length <= 0) {
                return callback([]);
            }
            const out = [];
            for (let i = 0; i < re.data.length; i++) {
                const one = re.data[i];
                const arr = one.split('|');
                out.push({ picId: arr[0], txt: arr[1], picUrl: arr[2] });
            }
            callback(out);
        });
    }


    /**
     * 上报用户排行榜数据
     * @param gameId 用于区分游戏以及不同的排行榜
     * @param openId 需要openId,会从上报昵称的表中按openId取昵称等信息
     * @param score 用于排行计算的值
     * @param callback 返回{oldRank: number, newRank: number}，即上报数据后用户自己的当前排名,null为异常
     */
    static leaderBoradUpdate(gameId: string, openId: string, score: number, callback: (re: { oldRank: number, newRank: number }) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/leaderBoradUpdate', { gameId, userId: openId, score }, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                callback(null);
                return;
            }
            // loskc.log('re', re);
            if (re.code) {
                loskc.err(re.code);
                callback(null);
                return;
            }
            callback(re.data);
        });
    }

    /**
     * 获取用户排行榜排名
     * @param gameId 用于区分游戏以及不同的排行榜
     * @param openId 需要openId,会从上报昵称的表中按openId取昵称等信息
     * @param callback 返回newRank，即上报数据后用户自己的当前排名,-1为异常或无排名
     */
    static leaderBoradRank(gameId: string, openId: string, callback: (newRank: number) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/leaderBoradRank', { gameId: gameId, userId: openId }, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                callback(-1);
                return;
            }
            // loskc.log('re', re);
            if (re.code) {
                loskc.err(re.code);
                callback(-1);
                return;
            }
            callback(re.data);
        });
    }


    /**
     * 拉取实时排行榜
     * @param gameId 排行榜id
     * @param callback 参数为按score倒排的数组
     */
    static getLeaderBorad(gameId: string, callback: (list: Array<{
        nickName: string,
        avatar: string,
        score: number, //排行数值
    }>) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/getLeaderBorad', { gameId }, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                callback([]);
                return;
            }
            // loskc.log('re', re, re.ts);
            if (re.code) {
                loskc.err(re.code);
                callback([]);
                return;
            }
            callback(re.data);
        });
    }


    /**
     * 上报用户排行榜数据
     * @param gameId 用于区分游戏以及不同的排行榜
     * @param myUserId 用户自己id
     * @param myUserName 用户昵称
     * @param userIcon 用户icon
     * @param value 用于排行计算的值
     */
    static reportToRankList(gameId: string, myUserId: string, myUserName: string, userIcon: string, value: string, callback?: () => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/phbUpdate', { userId: myUserId, gameId: gameId, userName: myUserName, userIcon, sortVal: value }, (err: any) => {
            callback && callback();
            if (err) {
                loskc.err(err);
                return;
            }
            // loskc.log('re', re);
        });
    }

    /**
     * 拉取排行榜
     * @param gameId 排行榜id
     * @param callback 参数为按value倒排的数组
     */
    static getRankList(gameId: string, callback: (list: Array<{
        'userId': string,
        'userName': string,
        'userIcon': string,
        'sortVal': number, //排行数值
    }>) => void) {
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/gameApi/phbList', { gameId }, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                callback([]);
                return;
            }
            // loskc.log('re', re);
            if (re.code) {
                loskc.err(re.code);
                callback([]);
                return;
            }
            callback(re.data);
        });
    }


    /**
     * 加载远程存档
     * @param openId 
     * @param callback 
     * @returns 
     */
    static loadFromRemote(openId: string, callback: (err: any, saveData?: any) => void): void {
        //web为测试，不上报数据
        if (losChannel.isConfRemote) {
            callback(null);
            return;
        }

        loskc.log('加载远程存档开始....', openId);
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/userSave/getUserData', { 'game_id': losChannel.gameName + losChannel.instance().channel, 'user_id': openId }, (err, re) => {
            if (err) {
                loskc.err(err);
                callback(err);
                return;
            }
            // loskc.log('loadFromRemote完成:' + JSON.stringify(re));
            if (re.code === 0 && re.data) {
                delete re.data.user_id;
                delete re.data.game_id;
                delete re.data._id;

                // 这里看情况是否存本地
                // loskc.saveUpdate(re.data.saveData);
                loskc.log('远程存档加载完成');
                callback(null, re.data.saveData);
                return;
            }
            callback(null);
        });
    }


    /**
     * 执行远程存档
     * @param openId 
     * @param saveData 
     * @returns 
     */
    static saveToRemote(openId: string, saveData: any, isTipShow: boolean = false): void {
        //web为测试，不存远程
        if (losChannel.isConfRemote) {
            return;
        }
        this.instance().getChannel().jpost('https://ga.gamejym.com/fcm/userSave/saveUserData', { 'game_id': losChannel.gameName + losChannel.instance().channel, 'user_id': openId, saveData }, (err, re) => {
            if (err) {
                loskc.err(err);
                return;
            }
            loskc.log('saveToRemote完成:' + JSON.stringify(re));
            // if (isTipShow) {
            //     losTipManager.showHomeTip("数据上传成功", null, 3);
            // }
        });
    }
    /** 分享图上报次数 */
    static picShareTo(gameId: string, wxPicId: string) {
        const reqObj = {
            'game': gameId,
            'query': 'aaa',
            'v': '1.2.0',
            's': 's',
            'wxPicId': wxPicId,
        };
        this.instance().getChannel().jpost('https://dk.gametdd.com/htApi/ht_api/shareTo', reqObj, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                return;
            }
            // loskc.log('re', re);
        });
    }
    /** 分享图上报次数 */
    static picShareFrom(gameId: string, wxPicId: string) {
        const reqObj = {
            'game': gameId,
            'query': 'aaa',
            'v': '1.2.0',
            's': 's',
            'wxPicId': wxPicId,
        };
        this.instance().getChannel().jpost('https://dk.gametdd.com/htApi/ht_api/shareFrom', reqObj, (err: any, re: any) => {
            if (err) {
                loskc.err(err);
                return;
            }
            // loskc.log('re', re);
        });
    }


    getPara(key: string): string {
        return this.getChannel().getPara(key);
    }

    getChannel(): losChannelWeb {
        return this.channelMap.get(this.channel);
    }
    getGameName() {
        return this.getChannel().getGameName();
    }
    /** 获取软著文字 */
    getRuanZhu(): string {
        return this.getChannel().getRuanZhu();
    }

    exit() {
        this.getChannel().exit();
    }

    /** getSystemInfoSync */
    getSysInfo(): any {
        return this.getChannel().getSysInfo();
    }
    getLaunchOpt(): any {
        return this.getChannel().getSysInfo();
    }

    /* 是否有隐私政策 */
    hasPrivacy(): boolean {
        return this.getChannel().hasPrivacy();
    }
    privacyReject(): number {
        return this.getChannel().privacyReject();
    }
    /** 同意隐私政策 */
    privacyAgree(): number {
        return this.getChannel().privacyAgree();
    }
    privacyNextPage(pageType: number): string {
        return this.getChannel().privacyNextPage(pageType);
    }
    privacyPrePage(pageType: number): string {
        return this.getChannel().privacyPrePage(pageType);
    }
    privacyPage1(pageType: number): string {
        return this.getChannel().privacyPage1(pageType);
    }

    getCtrl(key: string): number {
        return this.getChannel().getCtrl(key);
    }

    getPrivacyShort(): string {
        return this.getChannel().getPrivacyShort();
    }

    getPrivacy(): string {
        return this.getChannel().getPrivacy();
    }

    init(loginCall: (code?: number) => void) {
        //注意web渠道不会调loginCall
        this.getChannel().init(loginCall);
    }
    login({ successCall, failCall }: { successCall: () => void, failCall: (code: number) => void }): void {
        this.getChannel().login({ successCall, failCall });
    }
    /** 是否支持分享 */
    canShare(): boolean {
        return this.getChannel().canShare();
    }

    /** 分享 */
    shareAppMessage(paras: { title: string, act: string, adsid: string }, sucCall: any = null, failCall: any = null) {
        this.getChannel().shareAppMessage(paras, sucCall, failCall);
    }


    /** 复制到剪贴板 */
    copyToClip(contentStr: string, callback: (err?: string) => void) {
        this.getChannel().copyToClip(contentStr, callback);
    }


    showVideo(paras: { sucCall: any, failCall: any, endCall: any, posName?: string; adsid?: string } = null) {
        this.getChannel().showVideo(() => {
            paras.sucCall && paras.sucCall()
        }, () => {
            paras.endCall && paras.endCall()
        })
    }
    canSupportAddShortcut(): boolean {
        return this.getChannel().canSupportAddShortcut()
    }
    canSupportCommonUse(): boolean {
        return this.getChannel().canSupportCommonUse();
    }
    canSupportSideBar(): boolean {
        return this.getChannel().canSupportSideBar()
    }
    needShowPrivacy(): boolean {
        return this.getChannel().needShowPrivacy()
    }
    showSideBar(call?: Function) {
        this.getChannel().showSidebar(call)
    }

    gird9IconClick() {
        this.getChannel().gird9IconClick();
    }

    /** 9宫格 */
    showGird9(): void {
        this.getChannel().showGird9();
    }

    /** 是否主动(定时)显示9宫格 */
    canAutoGird9(): boolean {
        return this.getChannel().canAutoGird9();
    }

    closeGird9(): void {
        this.getChannel().closeGird9();
    }

    showBanner(isForce: boolean = false, styleFn: any = null, where: string = null): void {
        this.getChannel().showBanner(isForce, styleFn, where);
    }

    closeBanner(): void {
        this.getChannel().closeBanner();
    }

    showBannerByTime(isForce: boolean = false) {
        this.getChannel().showBannerByTime(isForce);
    }

    closeBannerByTime() {
        this.getChannel().closeBannerByTime();
    }

    showResidentBanner(): void {
        this.getChannel().showResidentBanner();
    }
    closeResidentBanner(): void {
        this.getChannel().closeResidentBanner();
    }

    checkNativeInsert(adKey: string): boolean {
        return this.getChannel().checkNativeInsert(adKey);
    }

    loadNative(adKey: string, callback: (adList: any, newAdKey: string) => void) {
        this.getChannel().loadNative(adKey, callback);
    }

    /** 找到当前任意一个原生并触发点击 */
    findAndReport() {
        this.getChannel().findAndReport();
    }
    reportAdShow(adId: string) {
        this.getChannel().reportAdShow(adId);
    }
    reportAdClick(adId: string) {
        this.getChannel().reportAdClick(adId);
    }

    closeNative(adKey: string) {
        this.getChannel().closeNative(adKey);
    }
    /** native广告,adKey为paraMap中的key,返回原生load成功的资源 */
    getNativeData(adKey: string): any {
        this.getChannel().getNativeData(adKey);
    }

    /** customAd */
    showCustomAd(isForce?: boolean, style?: any, showVideoOnClose: boolean = false): void {
        this.getChannel().showCustomAd(isForce, style, showVideoOnClose);
    }
    closeCustomAd(isBanner: boolean = false): void {
        this.getChannel().closeCustomAd(isBanner);
    }


    /** inter */
    showInter(isForce: boolean = false): void {
        this.getChannel().showInter(isForce);
    }
    closeInter(): void {
        this.getChannel().closeInter();
    }
    loadMultiInter() {
        this.getChannel().loadMultiInter()
    }
    showMultiInter(num: number, style?: any) {
        this.getChannel().showMultiInter(num, style)
    }

    checkShortcut(paras: { sucCall: any, failCall: any }) {
        this.getChannel().checkShortcut(paras);
    }

    addShortcut(paras: { sucCall: any, failCall: any }): void {
        this.getChannel().addShortcut(paras);
    }
    checkCommonUse(paras: { sucCall: any, failCall: any }): void {
        this.getChannel().checkCommonUse(paras);
    }
    addCommonUse(paras: { sucCall: any, failCall: any }): void {
        this.getChannel().addCommonUse(paras);
    }
    recorderStart() {
        this.getChannel().recorderStart();
    }

    recorderStop() {
        this.getChannel().recorderStop();
    }

    /** 获取录屏时长，单位毫秒 */
    getRecordTime(): number {
        return this.getChannel().getRecordTime();
    }
    shareVideo(callback: any = null) {
        this.getChannel().shareVideo(callback);
    }

    /** 互推跳转 */
    jumpTo(appId: string, sucCall = () => { }, failCall = () => { }, completeCall = () => { }) {
        this.getChannel().jumpTo(appId, sucCall, failCall, completeCall);
    }


    canMoreGame(): boolean {
        return this.getChannel().canMoreGame();
    }

    showComm() {
        if (this.getChannel().channel !== 'ios') {
            return;
        }
        this.getChannel()['showComm']();
    }

    showToast(msg: string, type?: string, mask?: boolean) {
        this.getChannel().showToast(msg, type, mask)
    }
    /**
     * 不同渠道特殊处理一些广告展示
     */
    doAction(type: any, param) {
        this.getChannel().doAction(type, param)
    }
    /**
     * 请求支付
     */
    requestGamePayment(sucCall?: () => void, failCall?: () => void) {
        this.getChannel().requestGamePayment(sucCall, failCall)
    }
    checkGamePayment(sucCall?: () => void, failCall?: () => void) {
        this.getChannel().checkGamePayment(sucCall, failCall)
    }
    canSupportPayment(): boolean {
        return this.getChannel().canSupportPayment()
    }
}
